package cn.demo.text.editor.strategy.format.process;

import cn.demo.text.editor.constant.RunParam;
import cn.demo.text.editor.constant.Str;
import cn.demo.text.editor.encrypt.ByteUtil;
import cn.demo.text.editor.encrypt.XorUtil;

import java.nio.charset.Charset;

public class PriFormat implements Format {

    private static final Charset charset = Charset.forName("UTF-8");


    @Override
    public String analysis(String actionName, String content) throws Exception {
        String key = RunParam.context.get(Str.SECRET_KEY);

        if (key == null || "".equals(key)) {
            throw new RuntimeException("Please enter password.");
        }
        if (actionName.equals(Str.SAVE_AS)) {
            byte[] encrypt = XorUtil.encrypt(content.getBytes(charset), ByteUtil.hexToByteArray(key));
            content = ByteUtil.bytesToHexString(encrypt);
        }
        if (actionName.equals(Str.OPEN)) {
            byte[] encrypt1 = XorUtil.encrypt(ByteUtil.hexToByteArray(content), ByteUtil.hexToByteArray(key));
            content = new String(encrypt1, charset);
        }
        return content;
    }
}
